import 'package:flutter/material.dart';

class DartToast {
  // 显示时长枚举
  static const int LENGTH_SHORT = 1;
  static const int LENGTH_LONG = 3;

  // 显示位置枚举
  static const String TOP = 'TOP';
  static const String CENTER = 'CENTER';
  static const String BOTTOM = 'BOTTOM';

  // 存储当前显示的 Toast
  static final Map<BuildContext, OverlayEntry> _currentToastEntries = {};

  /// 显示 Toast - 完全兼容 fluttertoast 参数
  static void showToast({
    required BuildContext context,
    required String msg,
    int toastLength = LENGTH_SHORT,
    String gravity = CENTER,
    Color backgroundColor = Colors.black87,
    Color textColor = Colors.white,
    double fontSize = 16.0,
    int timeInSecForIosWeb = 1,
    double borderRadius = 1.0, // 新增：圆角程度，默认1
    double opacity = 1.0, // 新增：透明度，默认1
  }) {
    // 移除之前的 Toast（如果有）
    _hideCurrentToast(context);

    // 创建 OverlayEntry
    final overlayEntry = OverlayEntry(
      builder: (context) => _ToastWidget(
        msg: msg,
        duration: Duration(seconds: toastLength),
        gravity: gravity,
        backgroundColor: backgroundColor.withOpacity(opacity), // 应用透明度
        textColor: textColor,
        fontSize: fontSize,
        borderRadius: borderRadius, // 传递圆角参数
        onDismiss: () {
          // 通过 context 来移除，避免循环引用
          _hideCurrentToast(context);
        },
      ),
    );

    // 插入到 Overlay
    final overlay = Overlay.of(context);
    overlay.insert(overlayEntry);

    // 保存当前 Toast 引用以便后续移除
    _currentToastEntries[context] = overlayEntry;

    // 自动移除
    Future.delayed(Duration(seconds: toastLength), () {
      _hideCurrentToast(context);
    });
  }

  // 隐藏当前 Toast
  static void _hideCurrentToast(BuildContext context) {
    final entry = _currentToastEntries[context];
    if (entry != null && entry.mounted) {
      entry.remove();
      _currentToastEntries.remove(context);
    }
  }

  // 快捷方法 - 短 Toast
  static void showShortToast({
    required BuildContext context,
    required String msg,
    String gravity = CENTER,
    Color backgroundColor = Colors.black87,
    Color textColor = Colors.white,
    double borderRadius = 1.0,
    double opacity = 1.0,
  }) {
    showToast(
      context: context,
      msg: msg,
      toastLength: LENGTH_SHORT,
      gravity: gravity,
      backgroundColor: backgroundColor,
      textColor: textColor,
      borderRadius: borderRadius,
      opacity: opacity,
    );
  }

  // 快捷方法 - 长 Toast
  static void showLongToast({
    required BuildContext context,
    required String msg,
    String gravity = CENTER,
    Color backgroundColor = Colors.black87,
    Color textColor = Colors.white,
    double borderRadius = 1.0,
    double opacity = 1.0,
  }) {
    showToast(
      context: context,
      msg: msg,
      toastLength: LENGTH_LONG,
      gravity: gravity,
      backgroundColor: backgroundColor,
      textColor: textColor,
      borderRadius: borderRadius,
      opacity: opacity,
    );
  }

  // 成功 Toast
  static void showSuccess({
    required BuildContext context,
    required String msg,
    int toastLength = LENGTH_SHORT,
    String gravity = CENTER,
    double borderRadius = 1.0,
    double opacity = 1.0,
  }) {
    showToast(
      context: context,
      msg: msg,
      toastLength: toastLength,
      gravity: gravity,
      backgroundColor: Colors.green,
      textColor: Colors.white,
      borderRadius: borderRadius,
      opacity: opacity,
    );
  }

  // 错误 Toast
  static void showError({
    required BuildContext context,
    required String msg,
    int toastLength = LENGTH_SHORT,
    String gravity = CENTER,
    double borderRadius = 1.0,
    double opacity = 1.0,
  }) {
    showToast(
      context: context,
      msg: msg,
      toastLength: toastLength,
      gravity: gravity,
      backgroundColor: Colors.red,
      textColor: Colors.white,
      borderRadius: borderRadius,
      opacity: opacity,
    );
  }

  // 警告 Toast
  static void showWarning({
    required BuildContext context,
    required String msg,
    int toastLength = LENGTH_SHORT,
    String gravity = CENTER,
    double borderRadius = 1.0,
    double opacity = 1.0,
  }) {
    showToast(
      context: context,
      msg: msg,
      toastLength: toastLength,
      gravity: gravity,
      backgroundColor: Colors.orange,
      textColor: Colors.white,
      borderRadius: borderRadius,
      opacity: opacity,
    );
  }

  // 手动隐藏 Toast
  static void cancel({BuildContext? context}) {
    if (context != null) {
      _hideCurrentToast(context);
    } else {
      // 隐藏所有 Toast
      for (final entry in _currentToastEntries.values) {
        if (entry.mounted) {
          entry.remove();
        }
      }
      _currentToastEntries.clear();
    }
  }
}

// Toast 组件
class _ToastWidget extends StatefulWidget {
  final String msg;
  final Duration duration;
  final String gravity;
  final Color backgroundColor;
  final Color textColor;
  final double fontSize;
  final double borderRadius; // 新增：圆角程度
  final VoidCallback onDismiss;

  const _ToastWidget({
    required this.msg,
    required this.duration,
    required this.gravity,
    required this.backgroundColor,
    required this.textColor,
    required this.fontSize,
    required this.borderRadius,
    required this.onDismiss,
  });

  @override
  _ToastWidgetState createState() => _ToastWidgetState();
}

class _ToastWidgetState extends State<_ToastWidget> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _opacityAnimation;

  @override
  void initState() {
    super.initState();

    _controller = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );

    _opacityAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _controller,
      curve: Curves.easeInOut,
    ));

    // 开始动画
    _controller.forward();

    // 结束动画
    Future.delayed(widget.duration - const Duration(milliseconds: 300), () {
      if (mounted) {
        _controller.reverse().then((_) {
          widget.onDismiss();
        });
      }
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Positioned(
      top: _getTopPosition(context),
      bottom: _getBottomPosition(context),
      left: 20,
      right: 20,
      child: FadeTransition(
        opacity: _opacityAnimation,
        child: Material(
          color: Colors.transparent,
          child: Center(
            child: Container(
              constraints: BoxConstraints(
                minWidth: 80, // 最小宽度
                maxWidth: MediaQuery.of(context).size.width * 0.8, // 最大宽度为屏幕宽度的80%
              ),
              padding: const EdgeInsets.symmetric(
                horizontal: 20, // 水平内边距
                vertical: 12,
              ),
              decoration: BoxDecoration(
                color: widget.backgroundColor,
                borderRadius: BorderRadius.circular(widget.borderRadius * 25), // 应用圆角程度
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.3),
                    blurRadius: 10,
                    offset: const Offset(0, 4),
                  ),
                ],
              ),
              child: Text(
                widget.msg,
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: widget.textColor,
                  fontSize: widget.fontSize,
                  fontWeight: FontWeight.w400,
                ),
                softWrap: true, // 允许文字换行
                overflow: TextOverflow.visible,
              ),
            ),
          ),
        ),
      ),
    );
  }

  double? _getTopPosition(BuildContext context) {
    switch (widget.gravity) {
      case DartToast.TOP:
        return MediaQuery.of(context).padding.top + 50;
      case DartToast.CENTER:
        return null;
      case DartToast.BOTTOM:
        return null;
      default:
        return null;
    }
  }

  double? _getBottomPosition(BuildContext context) {
    switch (widget.gravity) {
      case DartToast.TOP:
        return null;
      case DartToast.CENTER:
        return MediaQuery.of(context).size.height / 2;
      case DartToast.BOTTOM:
        return MediaQuery.of(context).padding.bottom + 50;
      default:
        return MediaQuery.of(context).padding.bottom + 50;
    }
  }
}